<?php

namespace App\Http\Controllers;

use App\BO\Product\ProductSkuInfoFactory;
use App\Entity\UserAddressEntity;
use App\Entity\UserEntity;
use App\Models\UserAddress;
use App\Services\Code\HttpResponse;
use App\Services\LocationService;
use App\Services\UserAddressService;
use App\Utils\UserLocationSessionUtil;
use App\VO\UserAddresses\Builder as UserAddressesVOBuilder;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

/**
 * @apiDefine address 地址管理接口
 *
 */
class UserAddressesController extends BaseController
{
    /**
     * @param Request $request
     * @return JsonResponse
     *
     * @api {get} /user/address 地址列表
     * @apiVersion 0.0.0
     * @apiName /user/address
     * @apiGroup UserAddress
     * @apiDescription 地址列表
     *
     * @apiSuccessExample {json} success:
     * {"code":200,"message":"ok","data":{"addresses":[{"id":289,"contact_name":"Good morning","contact_phone":"18672457160","full_address":"\u5317\u4eac\u5e02\u671d\u9633\u533a\u5b89\u534e\u6865Good morning","isdefault":0},{"id":303,"contact_name":"\u6768\u5e06","contact_phone":"18672457160","full_address":"\u5317\u4eac\u5e02\u671d\u9633\u533a\u5b89\u534e\u6865imyafadsf","isdefault":0},{"id":304,"contact_name":"\u90ed\u52c7","contact_phone":"18511057018","full_address":"\u676d\u5dde\u5e02\u6ee8\u6c5f\u533a\u897f\u5174fafsafasfafsa","isdefault":0},{"id":305,"contact_name":"\u6768\u5e06","contact_phone":"18672457160","full_address":"\u5317\u4eac\u5e02\u671d\u9633\u533a\u5b89\u534e\u6865fasfasafasf","isdefault":0},{"id":306,"contact_name":"\u6768\u5e06","contact_phone":"18672457160","full_address":"\u5317\u4eac\u5e02\u671d\u9633\u533a\u5b89\u534e\u6865\u6d4b\u4e00\u4e0b","isdefault":0},{"id":349,"contact_name":"\u6768\u6d0b","contact_phone":"18672457160","full_address":"\u6df1\u5733\u5e02\u798f\u7530\u533a\u5b89\u6258\u5c71\u56ed\u5c0f\u533a\u91cc","isdefault":0},{"id":356,"contact_name":"aaa123123","contact_phone":"13012345678","full_address":"\u5317\u4eac\u5e02\u671d\u9633\u533a\u5b89\u534e\u6865123123","isdefault":1},{"id":361,"contact_name":"aaa123","contact_phone":"13012345678","full_address":"\u5317\u4eac\u5e02\u4e1c\u57ce\u533axxxxx1234","isdefault":0}]}}
     * @apiErrorExample {json} fail:
     *     {"code":201,"message":"FAILED"}
     */
    public function index(Request $request)
    {
        $userEntity = $this->getUserEntity();
        $userModel = $userEntity->getOriginalModel();
        $addresses = $userModel->addresses;
        $vo = (new UserAddressesVOBuilder())->buildDetail([
            'addresses' => $addresses,
        ]);
        return $this->showJsonResult(200, 'ok', $vo);
    }

    /**
     * @param Request $request
     * @return JsonResponse
     *
     * @api {get} /user/address/productFilter 通过产品适用范围过滤地址列表
     * @apiVersion 0.0.0
     * @apiName /user/address/productFilter
     * @apiGroup UserAddress
     * @apiDescription 通过产品适用范围过滤地址列表
     *
     * @apiParam {int} user_id  用户ID
     * @apiParam {int} city_id  城市ID
     * @apiParam {int} productSkuId  skuid
     *
     * @apiSuccessExample {json} success:
     *     {"code":200,"message":"success","data":{"addresses":[{"id":388,"contact_name":"\u8d75\u5065","contact_phone":"17611188372","full_address":"\u6210\u90fd\u5e02\u91d1\u725b\u533a\u97e6\u5bb6\u78be\u6210\u90fd\u5047\u7684\u5047\u7684102\u53f7","isdefault":0,"enable":true},{"id":389,"contact_name":"\u627e\u627e","contact_phone":"17611188372","full_address":"\u5317\u4eac\u5e02\u671d\u9633\u533a\u5b89\u534e\u6865213213","isdefault":1,"enable":true}]}}
     * @apiErrorExample {json} fail:
     *     {"code":1090,"message":"FAILED"}
     */
    public function productFilter(Request $request)
    {
        $productSkuId = (int)$request->input('productSkuId');
        $cityId = (int)$request->input('city_id');
        try {
            $productSkuInfo = ProductSkuInfoFactory::getProductSkuInfo($productSkuId);
        } catch (\Throwable $e) {
            logException($e);
            return $this->showJsonResult(HttpResponse::CODE_FAIL);
        }
        $user = UserEntity::find($this->getUserId());

        //过滤不提供服务的地址
        $addresses = LocationService::filterNonProductServAddrByDB($productSkuInfo->getProductId(), $user->getOriginalModel()->addresses);

        $vo = (new UserAddressesVOBuilder())->buildDetail([
            'addresses' => $addresses,
        ]);
        return $this->successJsonResult($vo);
    }

    /**
     * 订单预览进到的地地添加
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function add(Request $request)
    {
        $cityId = (new UserLocationSessionUtil())->getLocationCityId();

        //添加地址页面
        $product_id = $request->product_id; //当前产品id

        //过滤不提供服务的地址
        $cityData = LocationService::getH5CityData($product_id);
        //保留当前城市的地址
        $cityData = LocationService::currentCityAddresses($cityId, $cityData);

        return view('user_addresses.add', ['address' => new UserAddress(), 'cityData' => $cityData,  'cityId' => $cityId]);
    }

    /**
     * @param Request $request
     * @return JsonResponse
     *
     * @api {post} /user/address/store 添加地址
     * @apiVersion 0.0.0
     * @apiName /user/address/store
     * @apiGroup UserAddress
     * @apiDescription 添加地址
     * @apiParam {String} address 地址
     * @apiParam {String} contact_name 联系人名称
     * @apiParam {String} contact_phone 联系人电话
     * @apiParam {Number} isdefault 是否默认地址
     * @apiParam {String} lat 纬度
     * @apiParam {String} lng 经度
     * @apiParam {String} province 城市名称
     * @apiParam {String} provinceid 城市id
     * @apiParam {String} city 城区名称
     * @apiParam {String} cityid 城区id
     * @apiParam {String} district 商圈名称
     * @apiParam {String} districtid 商圈id
     *
     * @apiSuccessExample {json} success:
     * {"code":200,"message":"ok","data":{}}
     * @apiErrorExample {json} fail:
     *     {"code":201,"message":"FAILED"}
     */
    public function store(Request $request)
    {
        $userId = $this->getUserId();
        $address = $request->only([
            'province',
            'city',
            'district',
            'provinceid',
            'cityid',
            'districtid',
            'address',
            'lng',
            'lat',
            'contact_name',
            'contact_phone',
            'isdefault',
        ]);
        UserAddressService::add($userId, $address);
        return $this->showJsonResult(200, 'ok', []);
    }

    /**
     * @param Request $request
     * @return JsonResponse
     *
     * @api {post} /user/address/update 地址修改
     * @apiVersion 0.0.0
     * @apiName /user/address/update
     * @apiGroup UserAddress
     * @apiDescription 地址修改
     * @apiParam {Number} id 地址 id
     * @apiParam {String} address 地址描述
     * @apiParam {String} contact_name 联系人名称
     * @apiParam {String} contact_phone 联系人电话
     * @apiParam {Number} isdefault 是否默认地址
     * @apiParam {String} lat 纬度
     * @apiParam {String} lng 经度
     * @apiParam {String} province 城市名称
     * @apiParam {String} provinceid 城市id
     * @apiParam {String} city 城区名称
     * @apiParam {String} cityid 城区id
     * @apiParam {String} district 商圈名称
     * @apiParam {String} districtid 商圈id
     *
     * @apiSuccessExample {json} success:
     * {"code":200,"message":"ok","data":{}}
     * @apiErrorExample {json} fail:
     *     {"code":201,"message":"FAILED"}
     */
    public function update(Request $request)
    {
        $userId = $this->getUserId();
        $address = $request->only([
            'id',
            'province',
            'city',
            'district',
            'provinceid',
            'cityid',
            'districtid',
            'address',
            'lng',
            'lat',
            'contact_name',
            'contact_phone',
            'isdefault',
        ]);
        UserAddressService::update($userId, $address);
        return $this->showJsonResult(200, 'ok', []);
    }

    /**
     * @param Request $request
     * @return JsonResponse
     *
     * @api {post} /user/address/delete 删除地址
     * @apiVersion 0.0.0
     * @apiName /user/address/delete
     * @apiGroup UserAddress
     * @apiDescription 删除地址
     * @apiParam {Number} id 地址 id
     *
     * @apiSuccessExample {json} success:
     * {"code":200,"message":"ok","data":{}}
     * @apiErrorExample {json} fail:
     *     {"code":201,"message":"FAILED"}
     */
    public function destroy(Request $request)
    {
        $userId = $this->getUserId();
        $request->only([
            'id',
            'user_id',
        ]);
        try {
            DB::beginTransaction();
            $addressModel = UserAddress::find($request->id);
            if (!$addressModel) {
                return $this->showJsonResult(201, '地址未找到');
            }
            $addressModel->delete();
            $defaultAddr = UserAddressService::getdefault($userId);
            if (!$defaultAddr) { // 没找到默认就得随便找一个改成默认
                UserAddress::query()
                    ->where('user_id', '=', $userId)
                    ->where('isdefault', '=', 1)
                    ->limit(1)// 一个就行
                    ->update(['isdefault' => 1]);
            }
            DB::commit();
        } catch (\Exception $e) {
            return $this->showJsonResult(500, 'failed', ['error' => $e->getMessage()]);
        }
        return $this->showJsonResult(200, 'ok', []);
    }

    /**
     * @param Request $request
     * @return JsonResponse
     *
     * @api {post} /user/address/info 获取地址某一个地址信息
     * @apiVersion 0.0.0
     * @apiName /user/address/info
     * @apiGroup UserAddress
     * @apiDescription 获取地址某一个地址信息
     * @apiParam {Number} id 地址 id
     *
     * @apiSuccessExample {json} success:
     *  {"code":200,"message":"ok","data":{"id":361,"user_id":260,"province":"\u5317\u4eac\u5e02","city":"\u4e1c\u57ce\u533a","district":"","provinceid":1,"cityid":101,"districtid":0,"address":"xxxxx1234","contact_name":"aaa123","contact_phone":"13012345678","isdefault":0,"lng":"","lat":"","gd_lng":"","gd_lat":"","last_used_at":null,"created_at":"2020-09-09 09:33:07","updated_at":"2020-09-09 09:33:07"}}
     * @apiErrorExample {json} fail:
     *     {"code":201,"message":"FAILED"}
     */
    public function info(Request $request)
    {
        $userAddressId = (int) $request->get('id');
        $userId = $this->getUserId();
        $userAddressModel = UserAddressService::getUserOneAddressInfo($userAddressId, $userId);
        if (!$userAddressModel) {
            return $this->showJsonResult(201, '用户地址未找到');
        }
        $addressEntity = new UserAddressEntity($userAddressModel);
        return $this->showJsonResult(200, 'ok', $addressEntity->toArray());
    }
}
